package com.boho.system.service;

/**
 * @File name:  LoginService.java 
 * @Create on:  2010-05-10
 * @Author   :  陈伟
 *
 * @ChangeList
 * ---------------------------------------------------
 * Date         Editor              ChangeReasons
 *
 **/


import java.sql.Connection;
import java.util.Date;

import cn.boho.framework.context.ActionContext;
import cn.boho.framework.exception.UserOperationException;
import cn.boho.framework.log.Logger;
import cn.boho.framework.po.DynaBeanMap;
import cn.boho.framework.po.POUtils;
import cn.boho.framework.service.MessageService;

import com.boho.common.Constant;
import com.boho.system.dao.TSysUserDao;
import com.boho.system.po.TUserPO;




/**
 * 登陆业务类
 * 
 */
public class LoginService{
	//日志
	private static Logger logger = new Logger(org.apache.log4j.Logger.getLogger(LoginService.class));
	
	/**
	 * 登陆
	 * @param atx
	 * @param loginName 用户账号
	 * @param password 密码
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static void login(ActionContext atx, String loginName, String password) throws Exception{
		Connection con = atx.getConection();
		Date date = new Date(); //用户操作时间
		String ip = atx.getRemoteAddr();//用户登录IP
		DynaBeanMap dbmUser = TSysUserDao.getUserByLoginName(con, loginName);
		//用户是否存在
		if(dbmUser == null){
			UserOperationException uoe = new UserOperationException();
			atx.setErrorContext("FSTI_SYS_USER_1002", MessageService.getMessage("FSTI_SYS_USER_1002"), uoe);
			throw uoe;
		}
		Integer userID = (Integer)dbmUser.get("USER_ID");//用户编号
		Integer isLock = Integer.valueOf(dbmUser.get("IS_LOCK").toString()); //用户锁定标识
		if(Constant.IS_LOCKED_TRUE.equals(isLock)){
			UserOperationException uoe = new UserOperationException();
			atx.setErrorContext("FSTI_SYS_USER_1009", MessageService.getMessage("FSTI_SYS_USER_1009"), uoe);
			throw uoe;
		}
		
		//更新用户登录信息
		TUserPO conditionTUserPO = new TUserPO();
		TUserPO valueTUserPO = new TUserPO();
		conditionTUserPO.setUserId(userID);
		valueTUserPO.setLastLoginTime(date);
		valueTUserPO.setLastLoginIp(ip);
//		POUtils.update(con, conditionTUserPO, valueTUserPO, false);
		
		//保存SESSION
		atx.setSessionValue(Constant.SESSION_USER_NO, userID);
		atx.setSessionValue(Constant.SESSION_USER_BEAN, dbmUser);
		
		//记录日志
		StringBuffer info = new StringBuffer();
		info.append("\n【登陆】")
			.append("\nIP："+ atx.getRemoteAddr())
			.append("\n操作用户ID："+atx.getSessionValue(Constant.SESSION_USER_NO).toString());
		logger.info(info.toString());
	}
	
	/**
	 * 登出
	 * @param atx
	 * @throws Exception
	 */
	public static void logout(ActionContext atx) throws Exception{
		//登出
		atx.httpSessionInvalidate();
	}
	
}
